package com.nth.rooster.authentication.dao;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.nth.rooster.authentication.beans.LoginBean;
import com.nth.rooster.core.entities.RamLogins;
import com.nth.rooster.core.utils.DBUtils;

@Component
public class AuthenticationDAO implements AuthenticationDaoI {

	static Logger LOGGER = Logger.getLogger(AuthenticationDAO.class);
	
	@Autowired
	private SessionFactory factory;

	public RamLogins login(LoginBean loginBean) {
		LOGGER.info("Entered::Authentication::AuthenticationDAO::login()::UserName"+ loginBean.getUsername());
		Session session = factory.openSession();
		Query query = session.createQuery("from RamLogins where username=:username  and password=:password");
		query.setString("username", loginBean.getUsername());
		query.setString("password", loginBean.getPassword());
		RamLogins ramLogins = (RamLogins)query.uniqueResult();
		if(ramLogins!=null)
		ramLogins.getRamUsers().getRamRoles();
		DBUtils.closeSession(session);

		LOGGER.info("Exit::Authentication::AuthenticationDAO::login()::UserName"+ loginBean.getUsername());

		return ramLogins;
	}

	public void updateLogin(RamLogins login) {
		LOGGER.info("Entered::Authentication::AuthenticationDAO::updateLogin()::UserName"+ login.getUsername());
		Session session = factory.openSession();
		Transaction transaction = session.beginTransaction();
		session.update(login);
		transaction.commit();
		DBUtils.closeSession(session);
		
		LOGGER.info("Entered::Authentication::AuthenticationDAO::updateLogin()::UserName"+ login.getUsername());
		
	}
}
